<?php

namespace Modules\ShopApi\Models;
use Modules\Admin\Models\User as UserModel;
use Illuminate\Support\Facades\DB; 
use Modules\Admin\Services\UserService;  
class ShopCollect extends BaseApiModel
{	
	
	/**	 
	 * @name  商品收藏	 
	 */
	public function product_collect($id){
		$user_info = (new UserService())->my();
		$data = ['user_id'=>$user_info['id'],'product_id'=>$id];
		$collect_id = $this->where($data)->value('id');
		if($collect_id){
			$res = $this->destroy($collect_id);
		}else{
			$data['created_at'] = date('Y-m-d H:i:s');
			$res = $this->insert($data);
		}
		if($res){
			return $this->api_success();
		}else{
			return $this->api_error();
		}
	}
	/**
     * @name  关联图片
     */
    public function product_one()
    {
        return $this->hasOne('Modules\ShopApi\Models\ShopProduct','id','product_id');
    }
	/**	 
	 * @name  我的收藏列表	 
	 */
	public function my_collect(){
		$user_info = (new UserService())->my();
		$list = $this->where(['user_id'=>$user_info['id']])->select('id','product_id','status')
				->whereHas('product_one',function($query){
					$query->where('status',1);
				})
				->with([
					'product_one'=>function($query){
						$query->select('id','name','image_id','money','sales','bazaar_money');
					},  
					'product_one.image_one'=>function($query){
						$query->select('id','url','open');
					}
				])
				->orderBy('id','desc')
				->paginate(config('shopapi.per_page_product'))
				->toArray();
		$list['data'] = $this->my_collect_data($list['data']);		
		return $this->api_success(['data'=>[
			'data'			=> $list['data'],
			'last_page'		=> $list['last_page'],
			'per_page'		=> $list['per_page'],
			'current_page'	=> $list['current_page'],
			'total' 		=> $list['total']
		]]);
	}
	/**
	 * @name  我的收藏列表数据格式化 
	 */
	private function my_collect_data($data){
		$http = getHttpType();	 	
		foreach($data as $k=>$v){
			$data[$k]['bazaar_money'] =  $v['product_one']['bazaar_money'];
			$data[$k]['money'] =  $v['product_one']['money'];
			$data[$k]['name'] =  $v['product_one']['name'];
			$data[$k]['sales'] =  $v['product_one']['sales'];
			if($v['product_one']['image_one']['open'] == 1){
				$data[$k]['image_url'] = $http . $v['product_one']['image_one']['url'];
			}else{
				$data[$k]['image_url'] = $v['product_one']['image_one']['url'];
			}
			unset($data[$k]['product_one']);
		}
		return $data;
	}
	/**	 
	 * @name  我的收藏查看	 
	 */
	public function my_collect_look($id){
		if($this->where(['id'=>$id])->update(['status'=>1])){
			return $this->api_success();
		}else{
			return $this->api_error();
		}
	}
}
